<template>
  <a-card style="position: relative">
    <div class="loading" v-if="loadingFlag"><a-spin size="large"/></div>
    <div>
      <a-space class="operator">
        <a-button @click="add" type="primary">新建</a-button>
      </a-space>
      <a-form layout="horizontal" style="display: none">
        <div>
          <a-row >
            <a-col :md="6" :sm="24" >
              <a-form-item label="选择园区" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                <a-select v-model="query.farmName" placeholder="请选择园区" @change="farmChange">
                  <a-select-option
                      v-for="(item, index) in farmList"
                      :key="index" :value="item.FarmId">
                    {{item.FarmName}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" >
              <a-form-item label="选择地块" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                <a-select v-model="query.greenHouseName" placeholder="请选择地块" @change="houseChange">
                  <a-select-option
                      v-for="(item, index) in greenHouseList"
                      :key="index" :value="item.GreenHouseId">
                    {{item.GreenHouseName}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" >
              <a-form-item label="选择设备" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                <a-select v-model="query.devName" placeholder="请选择设备" @change="devChange">
                  <a-select-option
                      v-for="(item, index) in devList"
                      :key="index" :value="item.DevCode">
                    {{item.DevName}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <div style="margin: 3px 0 0 8px;">
                <a-button type="primary" @click="search">查询</a-button>
<!--                <a-button style="margin-left: 8px" @click="dataInit">重置</a-button>-->
              </div>
            </a-col>
          </a-row>
        </div>
      </a-form>
      <standard-table :loading="loading"
          :rowKey="(data, index) => index"
          :columns="columns"
          :dataSource="visualList"
      >
        <span slot="disType" slot-scope="disType">
          <span v-if="disType.record.disType===0">电脑</span>
          <span v-if="disType.record.disType===1">手机</span>
        </span>
        <span slot="status" slot-scope="status">
          <span v-if="status.record.status=='online'" style="color: #40A636">在线</span>
          <span v-else style="color:#dd6161;">离线</span>
        </span>
        <span slot="createdTime" slot-scope="createdTime">
          {{timeFormat(createdTime.record.createdTime)}}
        </span>
        <div slot="action" slot-scope="{text, record, index}">
          <a style="margin-right: 8px" @click="editRecard(record, index)">
            <a-icon type="edit"/>基础信息
          </a>
          <a style="margin-right: 8px" @click="editVisual(record, index)">
            <a-icon type="edit"/>编辑组态
          </a>
          <a style="margin-right: 8px" @click="showVisual(record, index)">
            <a-icon type="edit"/>预览
          </a>
          <a-popconfirm title="确定删除?" @confirm="delRecord(record, index)">
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a href="#" style="margin-right: 8px; color: #f5222d"><a-icon type="delete" />删除</a>
          </a-popconfirm>
        </div>
      </standard-table>
    </div>
    <a-modal
        :title="modalTitle"
        width="900px"
        :visible="visible"
        @ok="confirm"
        @cancel="editCancel">
      <a-form-model
          ref="farmForm"
          :model="data"
          :rules="rules"
          :label-col="{span: 4}"
          :wrapper-col="{span: 14}">
        <a-form-model-item label="组态名称" prop="name">
          <a-input v-model="data.name" type="text" />
        </a-form-model-item>
        <a-form-model-item label="模版定义"  v-show="user_mobile==='18676789877'||user_mobile==='15264426299' || user_mobile=='15263653262'"><!--prop="FarmName"-->
          <a-radio-group v-model="data.isMould" name="radioGroup" :default-value="false">
            <a-radio :value="true">
              是
            </a-radio>
            <a-radio :value="false">
              否
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="模版类型"  ><!--prop="FarmName"-->
          <a-radio-group v-model="data.disType" name="radioGroup" :default-value="1">
            <a-radio :value="0">
              电脑
            </a-radio>
            <a-radio :value="1">
              手机
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="选择园区"  prop="farmId"><!--prop="FarmName"-->
          <a-select v-model="data.farmId" placeholder="请选择园区" @change="farmChange" :disabled="data.visualId ? true : false">
            <a-select-option
                v-for="(item, index) in farmList"
                :key="index" :value="item.FarmId">
              {{item.FarmName}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="选择地块" prop="greenHouseId">
          <a-select v-model="data.greenHouseId" placeholder="请选择地块" @change="houseChange" :disabled="data.visualId ? true : false">
            <a-select-option
                v-for="(item, index) in greenHouseList"
                :key="index" :value="item.GreenHouseId">
              {{item.GreenHouseName}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="选择设备" prop="devCode">
          <a-select v-model="data.devCode" placeholder="请选择设备" @change="devChange" :disabled="data.visualId ? true : false">
            <a-select-option
                v-for="(item, index) in devList"
                :key="index" :value="item.DevCode">
              {{item.DevName}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-card>
</template>

<script>
  import {mapGetters} from 'vuex'
  import {list} from '@/services/farm'
  import { FormModel } from 'ant-design-vue';
  import StandardTable from '@/components/table/StandardTable'
  import {list as greenHouseList} from "@/services/greenhouse";
  import {list as devList, listAll} from "@/services/dev";
  import {visualList,save,update,del, listByDev} from "@/services/visual";
  import moment from "moment/moment";
  const columns = [
    {
      title: '组态名称',
      dataIndex: 'name',
      //scopedSlots: { customRender: 'name' }
      key: 'name'
    },
    {
      title: '类型',
      dataIndex: 'disType',
      key: 'disType',
      scopedSlots: { customRender: 'disType' }
    },
    {
      title: '园区名称',
      dataIndex: 'farmName',
      //scopedSlots: { customRender: 'name' }
      key: 'farmName'
    },
    {
      title: '设备名称',
      dataIndex: 'devName',
      //scopedSlots: { customRender: 'name' }
      key: 'devName'
    },
    {
      title: '设备编号',
      dataIndex: 'devCode',
      key: 'devCode'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      scopedSlots: { customRender: 'status' }
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      scopedSlots: { customRender: 'createdTime' }
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: '400px',
      scopedSlots: { customRender: 'action' }
    }
  ]
  export default {
    name: 'FarmIndex',
    components: {
      StandardTable,
      FormModel
    },
    computed: {
      ...mapGetters('account', ['user_mobile']),
      timeFormat(e) {
        return e => {
          return moment(e).format('YYYY-MM-DD HH:mm:ss')
        }
      }
    },
    data () {
      return {
        loading: false,
        loadingFlag: false,
        visible: false,
        modalTitle: '',
        columns: columns,
        farmList: [],
        greenHouseList: [],
        devList: [],
        devListStr: '',
        visualList: [],
        dataIndex: null,
        query: {
          farmId: undefined,
          farmName: undefined,
          greenHouseId: undefined,
          greenHouseName: undefined,
          devId: undefined,
          devCode: undefined,
          devName: undefined
        },
        data: {
          visualId: undefined,
          farmId: undefined,
          farmName: undefined,
          greenHouseId: undefined,
          greenHouseName: undefined,
          devId: undefined,
          devName: undefined,
          name: undefined,
          disType:1,
          isMould:false
        },
        rules: {
          name: [
            { required: true, message: '请输入组态名称', trigger: 'blur' },
          ],
          devCode: [
            { required: true, message: '请选择设备', trigger: 'blur' },
          ],
          farmId: [
            { required: true, message: '请选择园区', trigger: 'blur' },
          ],
          greenHouseId: [
            { required: true, message: '请选择地块', trigger: 'blur' },
          ],
        }
      }
    },
    created() {
      this.getFarmList();
      this.getDevVisualList()
    },
    mounted() {
      this.$on('change', pagination => {
        console.log(pagination);
      })
    },
    methods: {
      //组态设备
      async getDevVisualList() {
        this.loadingFlag = true
        const res = await listAll()
        const devList = res.Data
        const devCodeList = res.Data.map(item => {
          return item.DevCode
        })
        const visual = await listByDev({devCodeList})
        this.visualList = visual.datas.map(item => {
          const detail = devList.find(v => v.FarmId == item.farmId)
          return {
            id: item.id,
            name: item.name,
            keycode: item.keycode,
            devCode: item.devCode,
            description: item.description,
            devModelId: item.devModelId,
            disType: item.disType,
            farmId: item.farmId,
            farmName: detail.FarmName,
            greenHouseId: detail.GreenHouseId,
            greenHouseName: detail.GreenHouseName,
            devName: detail.DevName,
            status: detail.Status,
            isMould: item.isMould,
            createdTime: item.createdTime
          }
        })
        this.devListStr = devCodeList.join(',')
        localStorage.setItem('devCodeList', this.devListStr)
        this.loadingFlag = false
      },
      async search() {
        if(!this.query.devCode) {
          this.$message.error('设备未选择')
          return
        }
        let visualLists = await visualList(this.query.devCode);
        console.log(visualLists)
        this.visualList=visualLists.datas;
      },
      async getDevList() {
        let res = await devList(this.query.greenHouseId)
        this.devList = res.Data
      },
      devChange(e) {
        this.query.devCode = e
      },
      houseChange(e) {
        this.query.greenHouseId = e
        this.queryInit()
        this.getDevList()
      },
      async getGreenHouseList() {
        let res = await greenHouseList(this.query.farmId)
        this.greenHouseList = res.Data
      },
      farmChange(e) {
        this.query.farmId = e
        this.queryInit(true)
        this.getGreenHouseList()
      },
      async getFarmList() {
        this.loading = true
        let res = await list()
        console.log(res)
        this.farmList = res.Data
        this.loading = false
      },
      showVisual(row) {
        console.log(row)
       window.open("visual/show.html?keyCode="+row.keycode);
      },
      editRecard(row, index) {
        console.log(row,index)
        this.dataIndex = index
        this.data = {...row}
        this.modalTitle = '编辑园区'
        this.visible = true
        this.query.farmId = row.farmId
        this.getGreenHouseList()
        this.query.greenHouseId = row.greenHouseId
        this.getDevList()
      },
      editVisual(row,index){
        console.log(row,index)
        window.open("visual/index.html?keyCode="+row.keycode);
      },
      delRecord(row, index) {
        if(!row.id) {
          this.$message.error('无效组态');
          return
        }
        console.log(index);
        del(row.id).then(res => {
          if(res.resp_code == 0) {
            this.$message.success("删除成功")
            this.getDevVisualList()
          } else this.$message.error("删除失败")
        }).catch(err => {
          console.log(err);
          this.$message.error("删除失败")
        })
      },
      add() {
        this.visible = true
        this.modalTitle = '新建组态'
      },
      confirm() {
        this.$refs.farmForm.validate(valid => {
          console.log(valid)
          // eslint-disable-next-line no-empty
          if (valid){
            console.log(this.data)
            this.data.model=1;
            save(this.data).then(res=>{
              console.log(res);
              if (res.resp_code==0){
                this.$message.success("保存成功")
                this.getDevVisualList()
              }else{
                this.$message.error(res.resp_msg)
              }
            }).catch(err =>{
              console.log(err);
              this.$message.error("编辑失败")
            })
            this.visible = false
          }
        })
      },
      editCancel() {
        this.visible = false
        this.data = this.$options.data().data
        this.$refs.farmForm.resetFields();
      },
      queryInit(type=false) {
        this.query.devName = undefined
        this.query.devId = undefined
        if(type) {
          this.query.greenHouseId = undefined
          this.query.greenHouseName = undefined
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .search{
    margin-bottom: 54px;
  }
  .fold{
    width: calc(100% - 216px);
    display: inline-block
  }
  .operator{
    margin-bottom: 18px;
  }
  @media screen and (max-width: 900px) {
    .fold {
      width: 100%;
    }
  }
  .loading {
    position: absolute;
    z-index: 99999;
    background: rgba(0,0,0,.1);
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
